{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Deep Learning Models -- A collection of various deep learning architectures, models, and tips for TensorFlow and PyTorch in Jupyter Notebooks.\n",
    "- Author: Sebastian Raschka\n",
    "- GitHub Repository: https://github.com/rasbt/deeplearning-models"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Sebastian Raschka \n",
      "\n",
      "CPython 3.6.1\n",
      "IPython 6.0.0\n",
      "\n",
      "tensorflow 1.2.0\n",
      "numpy 1.13.0\n"
     ]
    }
   ],
   "source": [
    "%load_ext watermark\n",
    "%watermark -a 'Sebastian Raschka' -v -p tensorflow,numpy"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Chunking an Image Dataset for Minibatch Training using NumPy NPZ Archives"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This notebook provides an example for how to organize a large dataset of images into chunks for quick access during minibatch learning. This approach uses NumPy .npz archive files and only requires having NumPy as a dependency so that this approach should be compatible with different Python-based machine learning and deep learning libraries and packages for further image (pre)processing and augmentation. \n",
    "\n",
    "While this approach performs reasonably well (sufficiently well for my applications), you may also be interested in TensorFlow's \"[Reading Data](https://www.tensorflow.org/programmers_guide/reading_data)\" guide to work with `TfRecords` and file queues.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 0. The Dataset"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's pretend we have a directory of images containing two subdirectories with images for training, validation, and testing. The following function will create such a dataset of images in JPEG format locally for demonstration purposes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting ./train-images-idx3-ubyte.gz\n",
      "Extracting ./train-labels-idx1-ubyte.gz\n",
      "Extracting ./t10k-images-idx3-ubyte.gz\n",
      "Extracting ./t10k-labels-idx1-ubyte.gz\n"
     ]
    }
   ],
   "source": [
    "# Note that executing the following code \n",
    "# cell will download the MNIST dataset\n",
    "# and save all the 60,000 images as separate JPEG\n",
    "# files. This might take a few minutes depending\n",
    "# on your machine.\n",
    "\n",
    "import numpy as np\n",
    "\n",
    "# load utilities from ../helper.py\n",
    "import sys\n",
    "sys.path.insert(0, '..') \n",
    "from helper import mnist_export_to_jpg\n",
    "\n",
    "np.random.seed(123)\n",
    "mnist_export_to_jpg(path='./')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "mnist_train subdirectories ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\n",
      "mnist_valid subdirectories ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\n",
      "mnist_test subdirectories ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "\n",
    "for i in ('train', 'valid', 'test'):\n",
    "    print('mnist_%s subdirectories' % i, os.listdir('mnist_%s' % i))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that the names of the subdirectories correspond directly to the class label of the images that are stored under it."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To make sure that the images look okay, the snippet below plots an example image from the subdirectory `mnist_train/9/`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(28, 28)\n"
     ]
    },
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAP8AAAD8CAYAAAC4nHJkAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAEUZJREFUeJzt3XuInFWax/HfozG31lztDfGWVghCEDajpSysLiOzMzqO\nqIPgBdEsqPGP2WFHB1RcdEVEg64jKou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/52m7OmPrCO6+yd3fKj7fJenQztKVPnaJcVWi\nivAfK+mTEV9/qs7a8tslrTCzNWa2uOrBjGLOiJ2RNkuaU+VgRpHdubmdvrGzdMc8do3seN1svOH3\nbWe6+0JJP5b0s+LlbUfy4d/ZOqldM6adm9tllJ2l/6zKx67RHa+brYrwb5R0/Iivjytu6wjuvrH4\nuEXSs+q83Yc/P7RJavFxS8Xj+bNO2rl5tJ2l1QGPXSfteF1F+FdLmm9mJ5rZREmXSXq+gnF8i5n1\nFG/EyMx6JP1Inbf78POSFhWfL5L0XIVj+QudsnNzvZ2lVfFj13E7Xrt72/9IOk/D7/j/n6R/rmIM\ndcZ1kqT/Lv68W/XYJD2p4ZeBX2v4vZGrJc2W9Jqk9yWtkDSrg8b2mIZ3c16n4aDNrWhsZ2r4Jf06\nSWuLP+dV/dglxlXJ48YVfkBQvOEHBEX4gaAIPxAU4QeCIvxAUIQfCIrwA0ERfiCo/wffKJCgsXnC\n5wAAAABJRU5ErkJggg==\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x1238aeba8>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "%matplotlib inline\n",
    "import matplotlib.image as mpimg\n",
    "import matplotlib.pyplot as plt\n",
    "import os\n",
    "\n",
    "some_img = os.path.join('./mnist_train/9/', os.listdir('./mnist_train/9/')[0])\n",
    "\n",
    "img = mpimg.imread(some_img)\n",
    "print(img.shape)\n",
    "plt.imshow(img, cmap='binary');"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note: The JPEG format introduces a few artifacts that we can see in the image above. In this case, we use JPEG instead of PNG. Here, JPEG is used for demonstration purposes since that's still format many image datasets are stored in."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Chunking Images into NumPy NPZ Archive Files"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The following wrapper function creates .npz archive files training, testing, and validation. It will group images together into integer arrays that are then saved as .npz archive files. The number of rows (images) in each .npz archive will be equal to the `archive_size` argument. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import glob\n",
    "\n",
    "\n",
    "def images_to_pickles(data_stempath='./mnist_', which_set='train', \n",
    "                      archive_size=5000, width=28, height=28, channels=1,\n",
    "                      shuffle=False, seed=None):\n",
    "    \n",
    "    if not os.path.exists('%snpz' % data_stempath):\n",
    "        os.mkdir('%snpz' % data_stempath)\n",
    "        \n",
    "    img_paths = [p for p in glob.iglob('%s%s/**/*.jpg' % \n",
    "                                   (data_stempath, which_set), recursive=True)]\n",
    "    if shuffle:\n",
    "        rgen = np.random.RandomState(seed)\n",
    "        paths = rgen.shuffle(img_paths)\n",
    "    \n",
    "    idx, file_idx = 0, 1\n",
    "    data = np.zeros((archive_size, height, width, channels), dtype=np.uint8)\n",
    "    labels = np.zeros(archive_size, dtype=np.uint8)\n",
    "    for path in img_paths:\n",
    "        if idx >= archive_size - 1:\n",
    "            idx = 0\n",
    "            savepath = os.path.join('%snpz' % data_stempath, '%s_%d.npz' % \n",
    "                                    (which_set, file_idx))\n",
    "            file_idx += 1\n",
    "            np.savez(savepath, data=data, labels=labels)\n",
    "\n",
    "        label = int(os.path.basename(os.path.dirname(path)))\n",
    "        image = mpimg.imread(path)\n",
    "        \n",
    "        if len(image.shape) == 2:\n",
    "            data[idx] = image[:, :, np.newaxis]\n",
    "        labels[idx] = label\n",
    "        idx += 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "images_to_pickles(which_set='train', shuffle=True, seed=1)\n",
    "images_to_pickles(which_set='valid', shuffle=True, seed=1)\n",
    "images_to_pickles(which_set='test', shuffle=True, seed=1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The .npz files we created are stored under a new directory, `mnist_npz`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['test_1.npz',\n",
       " 'test_2.npz',\n",
       " 'train_1.npz',\n",
       " 'train_2.npz',\n",
       " 'train_3.npz',\n",
       " 'train_4.npz',\n",
       " 'train_5.npz',\n",
       " 'train_6.npz',\n",
       " 'train_7.npz',\n",
       " 'train_8.npz',\n",
       " 'train_9.npz',\n",
       " 'valid_1.npz']"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "os.listdir('mnist_npz')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To check that the archiving worked correctly, we will now load one of those .npz archives. Note that we can now access each archive just like a python dictionary. Here the `'data'` key contains the image data and the `'labels'` key stores an array containing the corresponding class labels:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(5000, 28, 28, 1)\n",
      "(5000,)\n"
     ]
    }
   ],
   "source": [
    "data = np.load('mnist_npz/test_1.npz')\n",
    "print(data['data'].shape)\n",
    "print(data['labels'].shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Class label: 9\n"
     ]
    },
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAP8AAAD8CAYAAAC4nHJkAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAEfpJREFUeJzt3X2MVfWZB/DvIzC8DSjISBBwp8QXYkwWkhuySXWDujSA\nGqwQU/4gmGhpIlab1ATjJqz/STbbEhM2jXQlxU21hbRGQmQ3QIykcUGuCop1W10dBILDkCnvLyPD\ns3/MoZnqnOe53nPOPffyfD8J4c597rnnN4f5cmbm9yaqCiKK55qyG0BE5WD4iYJi+ImC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ygohp8oKIaf\nKCiGnyioptqi25vSa217nGXZ71ps3ry57mNvvPFGs75gwQKz7m0nbU2NbW9vN4/1rrk3JNsbtWkt\nS+5t333x4kWz7h2/bt261Nptt91mHvv555+b9VmzZpn1VsA7P1FQDD9RUAw/UVAMP1FQDD9RUAw/\nUVAMP1FQTdXPX+S0XG/6qLeM9JtvvplaGzVqlHmstYQ0ANx8881m3WP15WftK/f68c+fP2/WL1y4\nYNYt3lTo06dPm/Vbb701tbZz507z2OnTp5t17+up6CnmeeCdnygohp8oKIafKCiGnygohp8oKIaf\nKCiGnyiopuqM9OatW/r7+zO9t9cfbs1L987tvffo0aPNepaty71jvS22vfUAvOtqLcfuXRfPuHHj\nzLo1duOee+4xj8265Hkr4J2fKCiGnygohp8oKIafKCiGnygohp8oKIafKCi3s1JENgC4H8AxVb0j\nee45AD8EcGVR92dV9Q3vvVTV7C/3+k6tPmuvr72trc2se33G1tzwL774wjzWm/vtsa4ZYM/J966p\nN8bA09vba9ZXr15d93t7/ybedR07dmxqLes6B976D974iGZQy53/VwDmD/H8WlWdlfxxg09EzcUN\nv6ruAmD/905ELSfLz/w/FpEPRGSDiEzIrUVE1BD1hv8XAGYAmAXgKICfpb1QRFaISFVEqsePH6/z\ndESUt7rCr6rdqtqvqpcB/BLAHOO161W1oqqVSZMm1dtOIspZXeEXkSmDPvw+gAP5NIeIGqWWrr5X\nAcwFMElEDgP4FwBzRWQWAAXQBeBHBbaRiArghl9Vlw7x9Ev1nExE3LXYLcOGDUutWXPaa+H1dz/x\nxBOptSeffNI8duXKlWb94MGDZv2RRx4x61afdJbrDQCbNm0y62vXrjXru3fvTq15+x14ewJ0d3eb\n9alTp6bWvK8Xbx2ErOMjmgFH+BEFxfATBcXwEwXF8BMFxfATBcXwEwUl1tLKeatUKlqtVlPrXlus\nZaK9Kb1e1463BPX777+fWlu3bp157IYNG8y6x5seetddd6XWxo8fbx67f/9+s97V1WXWvamvc+ak\nDv7E9u3bzWM93hbdrTCtNm+VSgXVar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qpJ2vYcgDNl79ycbCgzZfDO0gAeBPAISrx2RrseRgnX\nrYw7/xwAn6rqZ6raB+A3ABaV0I6mp6q7AHx9I/hFADYmjzdi4Iun4VLa1hRU9aiqvpc8Pg3gys7S\npV47o12lKCP8UwEcGvTxYTTXlt8KYIeIvCsiK8puzBAmJ9umA8CXACaX2ZghuDs3N9LXdpZummtX\nz47XeeMv/L7pTlWdBWABgJXJt7dNSQd+Zmum7pqadm5ulCF2lv6rMq9dvTte562M8B8BMH3Qx9OS\n55qCqh5J/j4G4DU03+7D3Vc2SU3+PlZye/6qmXZuHmpnaTTBtWumHa/LCP9eALeIyHdEpA3ADwBs\nKaEd3yAiY5NfxEBExgL4Hppv9+EtAJYnj5cDeL3EtvyNZtm5OW1naZR87Zpux2tVbfgfAAsx8Bv/\n/wPwz2W0IaVdMwDsT/58VHbbALyKgW8Dv8LA70YeBXA9gJ0APgGwA8DEJmrbfwL4EMAHGAjalJLa\ndicGvqX/AMC+5M/Csq+d0a5SrhtH+BEFxV/4EQXF8BMFxfATBcXwEwXF8BMFxfATBcXwEwXF8BMF\n9f8fZNihoAoPoAAAAABJRU5ErkJggg==\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x1241b0668>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "plt.imshow(data['data'][0][:, :, -1], cmap='binary');\n",
    "print('Class label:', data['labels'][0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Loading Minibatches"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The following cell implements a class for iterating over the MNIST images, based on the .npz archives, conveniently. \n",
    "Via the `normalize` parameter we additionally scale the image pixels to [0, 1] range, which typically helps with gradient-based optimization in practice.\n",
    "\n",
    "The key functions (here: generators) are\n",
    "\n",
    "- load_train_epoch\n",
    "- load_valid_epoch\n",
    "- load_test_epoch\n",
    "\n",
    "These let us iterate over small chunks (determined via `minibatch_size`). Each of these functions will load the images from a particular .npz archive into memory (here: 5000 images) and yield minibatches of smaller or equal size (for example, 50 images at a time). Via the two shuffle parameters, we can further control if the images within each .npz archive should be shuffled, and if the order the .npz files are loaded should shuffled after each epoch. By setting `onehot=True`, the labels are converted into a onehot representation for convenience."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "class BatchLoader():\n",
    "    def __init__(self, minibatches_path, \n",
    "                 normalize=True):\n",
    "        \n",
    "        self.normalize = normalize\n",
    "\n",
    "        self.train_batchpaths = [os.path.join(minibatches_path, f)\n",
    "                                 for f in os.listdir(minibatches_path)\n",
    "                                 if 'train' in f]\n",
    "        self.valid_batchpaths = [os.path.join(minibatches_path, f)\n",
    "                                 for f in os.listdir(minibatches_path)\n",
    "                                 if 'valid' in f]\n",
    "        self.test_batchpaths = [os.path.join(minibatches_path, f)\n",
    "                                 for f in os.listdir(minibatches_path)\n",
    "                                 if 'train' in f]\n",
    "\n",
    "        self.num_train = 45000\n",
    "        self.num_valid = 5000\n",
    "        self.num_test = 10000\n",
    "        self.n_classes = 10\n",
    "\n",
    "\n",
    "    def load_train_epoch(self, batch_size=50, onehot=False,\n",
    "                         shuffle_within=False, shuffle_paths=False,\n",
    "                         seed=None):\n",
    "        for batch_x, batch_y in self._load_epoch(which='train',\n",
    "                                                 batch_size=batch_size,\n",
    "                                                 onehot=onehot,\n",
    "                                                 shuffle_within=shuffle_within,\n",
    "                                                 shuffle_paths=shuffle_paths,\n",
    "                                                 seed=seed):\n",
    "            yield batch_x, batch_y\n",
    "\n",
    "    def load_test_epoch(self, batch_size=50, onehot=False,\n",
    "                        shuffle_within=False, shuffle_paths=False, \n",
    "                        seed=None):\n",
    "        for batch_x, batch_y in self._load_epoch(which='test',\n",
    "                                                 batch_size=batch_size,\n",
    "                                                 onehot=onehot,\n",
    "                                                 shuffle_within=shuffle_within,\n",
    "                                                 shuffle_paths=shuffle_paths,\n",
    "                                                 seed=seed):\n",
    "            yield batch_x, batch_y\n",
    "            \n",
    "    def load_validation_epoch(self, batch_size=50, onehot=False,\n",
    "                         shuffle_within=False, shuffle_paths=False, \n",
    "                         seed=None):\n",
    "        for batch_x, batch_y in self._load_epoch(which='valid',\n",
    "                                                 batch_size=batch_size,\n",
    "                                                 onehot=onehot,\n",
    "                                                 shuffle_within=shuffle_within,\n",
    "                                                 shuffle_paths=shuffle_paths,\n",
    "                                                 seed=seed):\n",
    "            yield batch_x, batch_y\n",
    "\n",
    "    def _load_epoch(self, which='train', batch_size=50, onehot=False,\n",
    "                    shuffle_within=True, shuffle_paths=True, seed=None):\n",
    "\n",
    "        if which == 'train':\n",
    "            paths = self.train_batchpaths\n",
    "        elif which == 'valid':\n",
    "            paths = self.valid_batchpaths\n",
    "        elif which == 'test':\n",
    "            paths = self.test_batchpaths\n",
    "        else:\n",
    "            raise ValueError('`which` must be \"train\" or \"test\". Got %s.' %\n",
    "                             which)\n",
    "            \n",
    "        rgen = np.random.RandomState(seed)\n",
    "        if shuffle_paths:\n",
    "            paths = rgen.shuffle(paths)\n",
    "\n",
    "        for batch in paths:\n",
    "\n",
    "            dct = np.load(batch)\n",
    "\n",
    "            if onehot:\n",
    "                labels = (np.arange(self.n_classes) == \n",
    "                          dct['labels'][:, None]).astype(np.uint8)\n",
    "            else:\n",
    "                labels = dct['labels']\n",
    "\n",
    "            if self.normalize:\n",
    "                # normalize to [0, 1] range\n",
    "                data = dct['data'].astype(np.float32) / 255.\n",
    "            else:\n",
    "                data = dct['data']\n",
    "\n",
    "            arrays = [data, labels]\n",
    "            del dct\n",
    "            indices = np.arange(arrays[0].shape[0])\n",
    "\n",
    "            if shuffle_within:\n",
    "                rgen.shuffle(indices)\n",
    "\n",
    "            for start_idx in range(0, indices.shape[0] - batch_size + 1,\n",
    "                                   batch_size):\n",
    "                index_slice = indices[start_idx:start_idx + batch_size]\n",
    "                yield (ary[index_slice] for ary in arrays)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The following for loop will iterate over the 45,000 training examples in our MNIST training set, yielding 50 images and labels at a time (note that we previously set aside 5000 training example as our validation datast)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(50, 28, 28, 1)\n",
      "(50, 10)\n"
     ]
    }
   ],
   "source": [
    "batch_loader = BatchLoader(minibatches_path='./mnist_npz/', \n",
    "                           normalize=True)\n",
    "\n",
    "for batch_x, batch_y in batch_loader.load_train_epoch(batch_size=50, onehot=True):\n",
    "    print(batch_x.shape)\n",
    "    print(batch_y.shape)\n",
    "    break"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "One training epoch contains 45000 images\n"
     ]
    }
   ],
   "source": [
    "cnt = 0\n",
    "for batch_x, batch_y in batch_loader.load_train_epoch(batch_size=50, onehot=True):\n",
    "    cnt += batch_x.shape[0]\n",
    "    \n",
    "print('One training epoch contains %d images' % cnt)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "249 ms ± 14 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
     ]
    }
   ],
   "source": [
    "def one_epoch():\n",
    "    for batch_x, batch_y in batch_loader.load_train_epoch(batch_size=50, onehot=True):\n",
    "        pass\n",
    "    \n",
    "% timeit one_epoch()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As we can see from the benchmark above, an iteration over one training epoch (45k images) is relatively fast."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Similarly, we could iterate over validation and test data via \n",
    "\n",
    "- batch_loader.load_validation_epoch\n",
    "- batch_loader.load_test_epoch"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Training a Model using TensorFlow's `feed_dict`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The following code demonstrate how we can feed our minibatches into a TensorFlow graph using a TensorFlow session's `feed_dict`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Multilayer Perceptron Graph"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "\n",
    "##########################\n",
    "### SETTINGS\n",
    "##########################\n",
    "\n",
    "# Hyperparameters\n",
    "learning_rate = 0.1\n",
    "training_epochs = 15\n",
    "batch_size = 100\n",
    "\n",
    "# Architecture\n",
    "n_hidden_1 = 128\n",
    "n_hidden_2 = 256\n",
    "height, width = 28, 28\n",
    "n_classes = 10\n",
    "\n",
    "\n",
    "##########################\n",
    "### GRAPH DEFINITION\n",
    "##########################\n",
    "\n",
    "g = tf.Graph()\n",
    "with g.as_default():\n",
    "    \n",
    "    tf.set_random_seed(123)\n",
    "\n",
    "    # Input data\n",
    "    tf_x = tf.placeholder(tf.float32, [None, height, width, 1], name='features')\n",
    "    tf_x_flat = tf.reshape(tf_x, shape=[-1, height*width])\n",
    "    tf_y = tf.placeholder(tf.int32, [None, n_classes], name='targets')\n",
    "\n",
    "    # Model parameters\n",
    "    weights = {\n",
    "        'h1': tf.Variable(tf.truncated_normal([width*height, n_hidden_1], stddev=0.1)),\n",
    "        'h2': tf.Variable(tf.truncated_normal([n_hidden_1, n_hidden_2], stddev=0.1)),\n",
    "        'out': tf.Variable(tf.truncated_normal([n_hidden_2, n_classes], stddev=0.1))\n",
    "    }\n",
    "    biases = {\n",
    "        'b1': tf.Variable(tf.zeros([n_hidden_1])),\n",
    "        'b2': tf.Variable(tf.zeros([n_hidden_2])),\n",
    "        'out': tf.Variable(tf.zeros([n_classes]))\n",
    "    }\n",
    "\n",
    "    # Multilayer perceptron\n",
    "    layer_1 = tf.add(tf.matmul(tf_x_flat, weights['h1']), biases['b1'])\n",
    "    layer_1 = tf.nn.relu(layer_1)\n",
    "    layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])\n",
    "    layer_2 = tf.nn.relu(layer_2)\n",
    "    out_layer = tf.matmul(layer_2, weights['out']) + biases['out']\n",
    "\n",
    "    # Loss and optimizer\n",
    "    loss = tf.nn.softmax_cross_entropy_with_logits(logits=out_layer, labels=tf_y)\n",
    "    cost = tf.reduce_mean(loss, name='cost')\n",
    "    optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)\n",
    "    train = optimizer.minimize(cost, name='train')\n",
    "\n",
    "    # Prediction\n",
    "    correct_prediction = tf.equal(tf.argmax(tf_y, 1), tf.argmax(out_layer, 1))\n",
    "    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32), name='accuracy')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Training the Neural Network with Minibatches"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch: 001 | AvgCost: 0.467 | MbTrain/Valid ACC: 0.960/0.928\n",
      "Epoch: 002 | AvgCost: 0.222 | MbTrain/Valid ACC: 0.970/0.944\n",
      "Epoch: 003 | AvgCost: 0.166 | MbTrain/Valid ACC: 0.980/0.951\n",
      "Epoch: 004 | AvgCost: 0.134 | MbTrain/Valid ACC: 0.990/0.959\n",
      "Epoch: 005 | AvgCost: 0.112 | MbTrain/Valid ACC: 0.990/0.962\n",
      "Epoch: 006 | AvgCost: 0.096 | MbTrain/Valid ACC: 0.990/0.964\n",
      "Epoch: 007 | AvgCost: 0.083 | MbTrain/Valid ACC: 0.990/0.967\n",
      "Epoch: 008 | AvgCost: 0.073 | MbTrain/Valid ACC: 0.990/0.966\n",
      "Epoch: 009 | AvgCost: 0.064 | MbTrain/Valid ACC: 0.990/0.967\n",
      "Epoch: 010 | AvgCost: 0.057 | MbTrain/Valid ACC: 0.990/0.970\n",
      "Epoch: 011 | AvgCost: 0.050 | MbTrain/Valid ACC: 0.990/0.970\n",
      "Epoch: 012 | AvgCost: 0.044 | MbTrain/Valid ACC: 0.990/0.970\n",
      "Epoch: 013 | AvgCost: 0.039 | MbTrain/Valid ACC: 0.990/0.971\n",
      "Epoch: 014 | AvgCost: 0.035 | MbTrain/Valid ACC: 0.990/0.971\n",
      "Epoch: 015 | AvgCost: 0.031 | MbTrain/Valid ACC: 0.990/0.971\n",
      "Test ACC: 0.992\n"
     ]
    }
   ],
   "source": [
    "##########################\n",
    "### TRAINING & EVALUATION\n",
    "##########################\n",
    "\n",
    "batch_loader = BatchLoader(minibatches_path='./mnist_npz/', \n",
    "                           normalize=True)\n",
    "\n",
    "# preload small validation set\n",
    "# by unpacking the generator\n",
    "[valid_data] = batch_loader.load_validation_epoch(batch_size=5000, \n",
    "                                                   onehot=True)\n",
    "valid_x, valid_y = valid_data[0], valid_data[1]\n",
    "del valid_data\n",
    "\n",
    "with tf.Session(graph=g) as sess:\n",
    "    sess.run(tf.global_variables_initializer())\n",
    "\n",
    "    for epoch in range(training_epochs):\n",
    "        avg_cost = 0.\n",
    "\n",
    "        n_batches = 0\n",
    "        for batch_x, batch_y in batch_loader.load_train_epoch(batch_size=batch_size, \n",
    "                                                              onehot=True, \n",
    "                                                              seed=epoch):\n",
    "            n_batches += 1\n",
    "            _, c = sess.run(['train', 'cost:0'], feed_dict={'features:0': batch_x,\n",
    "                                                            'targets:0': batch_y.astype(np.int)})\n",
    "            avg_cost += c\n",
    "        \n",
    "        train_acc = sess.run('accuracy:0', feed_dict={'features:0': batch_x,\n",
    "                                                      'targets:0': batch_y})\n",
    "        \n",
    "        valid_acc = sess.run('accuracy:0', feed_dict={'features:0': valid_x,\n",
    "                                                      'targets:0': valid_y})  \n",
    "        \n",
    "        print(\"Epoch: %03d | AvgCost: %.3f\" % (epoch + 1, avg_cost / n_batches), end=\"\")\n",
    "        print(\" | MbTrain/Valid ACC: %.3f/%.3f\" % (train_acc, valid_acc))\n",
    "        \n",
    "        \n",
    "    # imagine test set is too large to fit into memory:\n",
    "    test_acc, cnt = 0., 0\n",
    "    for test_x, test_y in batch_loader.load_test_epoch(batch_size=100, \n",
    "                                                       onehot=True):   \n",
    "        cnt += 1\n",
    "        acc = sess.run(accuracy, feed_dict={'features:0': test_x,\n",
    "                                            'targets:0': test_y})\n",
    "        test_acc += acc\n",
    "    print('Test ACC: %.3f' % (test_acc / cnt))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
